﻿using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace RatingAuthor
{
  public class GenresLookup
  {
    private readonly Dictionary<string, int> _data = new Dictionary<string, int>();
    private readonly List<string> _indexes = new List<string>();

    public IEnumerable<string> Values { get { return _indexes; } }
    
    public int this[string str]
    {
      get
      {
        int res;
        if (!_data.TryGetValue(str, out res))
        {
          res = _indexes.Count;
          _indexes.Add(str);
          _data[str] = res;
        }
        return res;
      }
    }
    public string this[int idx]
    {
      get { return _indexes[idx]; }
    }
    public void Save(BinaryWriter writer)
    {
      writer.Write(_indexes.Count);
      foreach (var index in _indexes)
        writer.Write(index);
    }
    public static GenresLookup Load(BinaryReader reader)
    {
      var res = new GenresLookup();
      var count = reader.ReadInt32();
      for (int i = 0; i < count; i++)
      {
        var index = reader.ReadString();
        res._indexes.Add(index);
        res._data[index] = i;
      }
      return res;
    }
    public GenresSet Lookup(IEnumerable<string> genres)
    {
      return new GenresSet(genres.Select(g => this[g]));
    }
  }
}